package org.example.cloud.controller;

import org.example.cloud.bean.File;
import org.example.cloud.bean.Folder;
import org.example.cloud.result.Result;
import org.example.cloud.service.implementation.FileFolderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api") // 添加基础路
public class FileFolderController {
    @Autowired
    FileFolderService fileFolderService;

    private static final Logger logger = LoggerFactory.getLogger(FileFolderController.class);
    @CrossOrigin
    @GetMapping("/files")
    public ResponseEntity<?> getFileList(
            @RequestParam String username) {

        System.out.println("收到请求: /api/files, username=" + username); // 添加日志

        List<Folder> folders = fileFolderService.getFolders(username);
        List<File> files = fileFolderService.getFiles(username);

        Map<String, Object> response = new HashMap<>();
        response.put("folders", folders);
        response.put("files", files);

        return ResponseEntity.ok(response);
    }
    @PostMapping("/createDir")
    public Result createDirectory(
            @RequestParam String username,
            @RequestParam String parentPath,
            @RequestParam String dirName) {
        logger.debug("接收到的用户名: {}, 路径: {},文件名:{}", username, parentPath,dirName);
        boolean result =fileFolderService.createFolder(username, parentPath, dirName);
        if (result) {
            return Result.error(200, "创建成功");
        } else {
            return Result.error(200, "创建失败");
        }
    }

    @DeleteMapping("/deleteDir")
    public ResponseEntity<?> deleteDirectory(
            @RequestParam String username,
            @RequestParam String folderPath) {

        boolean result = fileFolderService.deleteFolder(username, folderPath);
        if (result) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().body("Failed to delete directory");
        }
    }

    @DeleteMapping("/deleteFile")
    public ResponseEntity<?> deleteFile(
            @RequestParam String username,
            @RequestParam String filePath) {

        boolean result = fileFolderService.deleteFile(username, filePath);
        if (result) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().body("Failed to delete file");
        }
    }

}
